


import logging
from django.dispatch import receiver
from myapp.signals import user_visited, user_activity

logger = logging.getLogger(__name__)

@receiver(user_visited)
def log_user_visit(sender, **kwargs):
    user = kwargs.get('user')
    meta = kwargs.get('request_meta')
    
    if user.is_anonymous:
        username = "Anonymous"
    else:
        username = user.username
    
    log_message = (
        f"访问记录: 用户 '{username}' 访问了 {meta['path']} "
        f"(IP: {meta['ip']}, 方法: {meta['method']})"
    )
    
    logger.info(log_message)
    print(f"[信号日志] {log_message}")  # 控制台输出演示

@receiver(user_activity)
def log_user_activity(sender, **kwargs):
    user = kwargs.get('user')
    activity_type = kwargs.get('activity_type')
    details = kwargs.get('details')
    
    log_message = (
        f"用户活动: {user.username} 执行了 '{activity_type}' 活动 "
        f"详情: {details}"
    )
    
    logger.info(log_message)
    print(f"[信号日志] {log_message}")  # 控制台输出演示
    
    # 更新用户活动统计（演示信号如何触发模型更新）
    user.last_activity = timezone.now()
    user.activity_count += 1
    user.save(update_fields=['last_activity', 'activity_count'])